package com.ly.lw.styledo.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.ly.lw.styledo.R;
import com.ly.lw.styledo.beancategorysecondinfo.SizeList;
import com.ly.lw.styledo.beancategorysecondinfo.SnapList;
import com.ly.lw.styledo.config.UrlCategory;
import com.ly.lw.styledo.fragment.CategorySecondPicFragment;
import com.ly.lw.styledo.fragment.CategorySecondShopFragment;
import com.ly.lw.styledo.fragment.CategorySecondSizeFragment;
import com.ly.lw.styledo.utils.FileUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.UMSsoHandler;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wxl
 *         推荐-二级详情
 */
public class CategorySecondInfoActivity extends FragmentActivity {

    /**
     * 首先在您的Activity中添加如下成员变量:社会化分享
     */
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");


    //图片详情
    private List<SnapList> snapShotImgList;
    //商品介绍
    private String prdDesc;
    //尺码详情
    private List<SizeList> sizeList;

    private int prdNo;//传参
    private ArrayList<Fragment> fragments;
    private int fragmentContentId = R.id.category_second_info_container; // 将被替换的区域的id
    private int currentTab; // 当前Tab页面索引

    @ViewInject(R.id.category_second_pic_ind)
    private TextView picView;
    @ViewInject(R.id.category_second_shop_ind)
    private TextView shopView;
    @ViewInject(R.id.category_second_size_ind)
    private TextView sizeView;

    @ViewInject(R.id.category_second_pic)
    private TextView pic;
    @ViewInject(R.id.category_second_shop)
    private TextView shop;
    @ViewInject(R.id.category_second_size)
    private TextView size;

    //等三方登录
    @ViewInject(R.id.second_login_name)
    private TextView loginName;
    @ViewInject(R.id.second_login_image)
    private ImageView loginImg;
    private String loginImgUrl;
    @ViewInject(R.id.second_login)
    private Button loginBtn;


//    @ResInject(id = R.color.simidared, type = ResType.Color)
//    private Drawable selectBg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_category_second_info);
        ViewUtils.inject(this);

        prdNo = getIntent().getIntExtra("prdNo", 0);
        initData();
//        initView();
        initShare();
        initBitmap();
    }

    private void initView() {
        fragments = new ArrayList<>();
        fragments.add(CategorySecondPicFragment.newInstance(prdNo));//图片
        fragments.add(CategorySecondShopFragment.newInstance(prdDesc));//商品介绍
        fragments.add(CategorySecondSizeFragment.newInstance(prdNo));//尺码

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(fragmentContentId, fragments.get(0));
        ft.commit();
    }

    /**
     * 标题栏点击事件
     *
     * @param v
     */
    @OnClick({R.id.category_second_pic, R.id.category_second_shop, R.id.category_second_size, R.id.second_back, R.id.second_share, R.id.second_login})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.category_second_pic:
                pic.setTextColor(getResources().getColor(R.color.simidared));
                picView.setBackgroundColor(getResources().getColor(R.color.simidared));

                shop.setTextColor(getResources().getColor(R.color.darkgray));
                shopView.setBackgroundColor(getResources().getColor(R.color.white));
                size.setTextColor(getResources().getColor(R.color.darkgray));
                sizeView.setBackgroundColor(getResources().getColor(R.color.white));

                threeChange(0);
                break;
            case R.id.category_second_shop:
                shop.setTextColor(getResources().getColor(R.color.simidared));
                shopView.setBackgroundColor(getResources().getColor(R.color.simidared));

                pic.setTextColor(getResources().getColor(R.color.darkgray));
                picView.setBackgroundColor(getResources().getColor(R.color.white));
                size.setTextColor(getResources().getColor(R.color.darkgray));
                sizeView.setBackgroundColor(getResources().getColor(R.color.white));

                threeChange(1);
                break;
            case R.id.category_second_size:
                size.setTextColor(getResources().getColor(R.color.simidared));
                sizeView.setBackgroundColor(getResources().getColor(R.color.simidared));

                pic.setTextColor(getResources().getColor(R.color.darkgray));
                picView.setBackgroundColor(getResources().getColor(R.color.white));
                shop.setTextColor(getResources().getColor(R.color.darkgray));
                shopView.setBackgroundColor(getResources().getColor(R.color.white));

                threeChange(2);
                break;
            case R.id.second_back://回退
                finish();
                break;
            case R.id.second_share://分享
                Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show();
                mController.openShare(this, false);
                break;
            case R.id.second_login://登录
//                Toast.makeText(this, "正在登录...", Toast.LENGTH_SHORT).show();
                initLogin();
                initLoginAccesstoken();
                break;
        }
    }

    /**
     * **********************切换fragment***********************
     */
    public void threeChange(int n) {
        Fragment fragment = fragments.get(n);
        FragmentTransaction ft = obtainFragmentTransaction(n);
        getCurrentFragment().onStop(); // 暂停当前tab
        if (fragment.isAdded()) {
            fragment.onStart(); // 启动目标tab的fragment onStart()
        } else {
            ft.add(fragmentContentId, fragment);
            ft.commit();
        }
        showTab(n);
    }


    public Fragment getCurrentFragment() {
        return fragments.get(currentTab);
    }


    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // 设置切换动画
//        if (index > currentTab) {
//            ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
//        } else {
//            ft.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_right_out);
//        }
        return ft;
    }

    private void showTab(int idx) {
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            FragmentTransaction ft = obtainFragmentTransaction(idx);
            if (idx == i) {
                ft.show(fragment);
            } else {
                ft.hide(fragment);
            }
            ft.commit();
        }
        currentTab = idx; // 更新目标tab为当前tab
    }

    /**
     * *********************************************
     */

    private RequestParams getRequestParams() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("target_width", "600");
        params.addBodyParameter("prd_no", prdNo + "");
        params.addBodyParameter("appVersion", "1.4.6");
        params.addBodyParameter("os", "android");
        params.addBodyParameter("osVersion", "4.1.2");
        return params;
    }

    private void initData() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = getRequestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, UrlCategory.CATEGORY_SECOND_INFO, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;

                try {
                    prdDesc = new JSONObject(result).optJSONObject("result").optJSONObject("product").optString("prd_desc");
                    initView();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }


    /**
     * 社会化分享
     */
    private void initShare() {
        // 设置分享内容
        mController.setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能，http://www.umeng.com/social");
        // 设置分享图片, 参数2为图片的url地址
        mController.setShareMedia(new UMImage(this, "http://www.umeng.com/images/pic/banner_module_social.png"));
        // 设置分享图片，参数2为本地图片的资源引用
        //mController.setShareMedia(new UMImage(getActivity(), R.drawable.icon));
        // 设置分享图片，参数2为本地图片的路径(绝对路径)
        //mController.setShareMedia(new UMImage(getActivity(),
        //                                BitmapFactory.decodeFile("/mnt/sdcard/icon.png")));

        // 设置分享音乐
        //UMusic uMusic = new UMusic("http://sns.whalecloud.com/test_music.mp3");
        //uMusic.setAuthor("GuGu");
        //uMusic.setTitle("天籁之音");
        // 设置音乐缩略图
        //uMusic.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
        //mController.setShareMedia(uMusic);

        // 设置分享视频
        //UMVideo umVideo = new UMVideo(
        //          "http://v.youku.com/v_show/id_XNTE5ODAwMDM2.html?f=19001023");
        // 设置视频缩略图
        //umVideo.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
        //umVideo.setTitle("友盟社会化分享!");
        //mController.setShareMedia(umVideo);

    }

    /**
     * 第三方登录
     */
    UMSocialService mControllerLogin = UMServiceFactory.getUMSocialService("com.umeng.login");
//    UMSocialService.doOauthVerify(Context context,SHARE_MEDIA platform, SocializeListeners.UMAuthListener listener);

    //        在新浪微博登录按钮中实现下面的方法，点击按钮则弹出新浪微博登录页面
    private void initLogin() {
        mControllerLogin.doOauthVerify(this, SHARE_MEDIA.SINA, new SocializeListeners.UMAuthListener() {
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                if (value != null && !TextUtils.isEmpty(value.getString("uid"))) {
                    Toast.makeText(getApplicationContext(), "授权成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "授权失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
            }

            @Override
            public void onStart(SHARE_MEDIA platform) {
            }
        });
    }

    //获取accesstoken及用户资料
    private void initLoginAccesstoken() {
        mControllerLogin.getPlatformInfo(CategorySecondInfoActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMDataListener() {
            @Override
            public void onStart() {
                Toast.makeText(CategorySecondInfoActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {
                if (status == 200 && info != null) {
                    StringBuilder sb = new StringBuilder();
                    Set<String> keys = info.keySet();
                    for (String key : keys) {
                        sb.append(key + "=" + info.get(key).toString() + "\r\n");
                        if ("screen_name".equals(key)) {
                            loginName.setText(info.get(key).toString());
                        } else if ("profile_image_url".equals(key)) {
                            loginImgUrl = info.get(key).toString();
                            if (loginImgUrl != null) {//下载头像
                                bitmapUtils.display(loginImg, loginImgUrl);
                                loginBtn.setText("退出");
                            }
                        }
                    }
                    Log.d("TestData", sb.toString());

                } else {
                    Log.d("TestData", "发生错误：" + status);
                }
            }
        });
    }


    //配置sina SSO(免登录)开关-->设置新浪SSO handler,添加相关回调
//    在对应的activity中实现onActivityResult方法, 并添加如下代码
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mControllerLogin.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
//App Key   190079412
    //App Secret    78216c3c762409acc297fa666f020aae


    //下载头像图片
    private BitmapUtils bitmapUtils;

    private void initBitmap() {
        bitmapUtils = new BitmapUtils(getApplicationContext(), FileUtils.getImageCache());
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.ic_logo_small);
        bitmapUtils.configDefaultLoadingImage(R.mipmap.ic_logo_small);

        AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(1000);
        bitmapUtils.configDefaultImageLoadAnimation(animation);
        bitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);//设置图片压缩类型

        bitmapUtils.configMemoryCacheEnabled(true);
        bitmapUtils.configDiskCacheEnabled(true);
    }


}